<?php
    /**
    * Prayed Confirm
    * 
    * @author: trungdt
    * @since: Mar 11, 2011 
    * @version: 1.0
    * 
    * Change logs
    */

    if (!defined("EXPONENT")) exit("");
    $demand = null;        
    // build localtion
    $loc=null;
    $loc->mod="demandmodule";

    if (isset($_POST['id'])) {
        $demand = $db->selectObject('demands', 'id='.intval($_POST['id']));
    } 

    //if (exponent_permissions_check("manage",$loc)) {   
    // we can continue if 
    // - this user has administrate or approve demand permission
    // - this user is the owner of this record (post new) 
    if (exponent_users_isLoggedIn() && isset($demand->id)) 
    {
        $temp=$db->selectObject("demand_praydetail","user_id = {$user->id} AND demand_id = {$demand->id} ");
        $ret=null;
        $ret->id=$demand->id;
        if ($temp != null)
        {
            $ret->status=1; // confirmed
            $temp->add_time=$temp->add_time-(7+$user->time_belt)*3600; // convert form GMT+7 to local time
            $ret->content="Bạn đã xác nhận vào lúc ".date('d/m/Y h:i:s',$temp->add_time). " (GMT {$user->time_belt})";
        }
        else
        { // not confirm, continue confirming
            $ret->status=0; // normal confirm
            
            $time=aboid_getCurrentTime();
            $day=date("d",$time);
            $month=date("m",$time);
            $year=date("Y",$time);
            
            $sql="INSERT INTO {$db->prefix}demand_praydetail(demand_id, user_id, add_time, vday, vmonth, vyear) VALUES ({$demand->id}, {$user->id}, {$time}, {$day}, {$month}, {$year} )";
            $db->sql($sql);
            $sql="UPDATE {$db->prefix}demands 
                  SET pray_count=pray_count+1 WHERE id = {$demand->id}";
            $db->sql($sql);
            //
            $time=$time-(7+$user->time_belt)*3600; // From GMT +7 to local time
            $ret->title="Bạn đã xác nhận vào lúc ".date('d/m/Y h:i:s',$time) ."(GMT {$user->time_belt})";
            $ret->content="Cầu nguyện (".($demand->pray_count+1)." người)";
            // 
        }
        echo json_encode($ret);
    } else {
       $ret=null;
       $ret->id=intval($_REQUEST['id']);
       $ret->status=1; // confirmed
       $ret->content='Bạn cần đăng nhập trước khi thực hiện thao tác này';
       echo json_encode($ret);
    }
?>
